package com.xujiu.caigoumall.system.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xujiu.caigoumall.system.entity.Users;
import com.xujiu.caigoumall.system.mapper.UsersMapper;
import com.xujiu.caigoumall.system.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xujiu.caigoumall.util.jwtToken;
import com.xujiu.caigoumall.system.entity.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户  服务实现类
 *
 * @author 许久龙
 * @since 2022-02-21
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    UsersMapper usersMapper;
    @Autowired
    jwtToken jwtToken;

    @Override
    @Transactional
    public ResultVO regist(Users users) {
        synchronized (this) {
            String username = users.getUsername();
            String password = users.getPassword();
            Users user = new Users();
            //查询数据库 如果没有此用户id 则注册
            QueryWrapper<Users> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            List<Users> users1 = usersMapper.selectList(wrapper);
            if (users1 == null || users1.size() == 0) {
                //对密码进行MD5加密
                String passwordMD5 = SecureUtil.md5(password);
                user.setUsername(username);
                user.setPassword(passwordMD5);
                user.setUserImg("img/default.png");
                int insert = usersMapper.insert(user);
                if (insert > 0) {
                    return new ResultVO(200, "注册成功", null);
                }
                return new ResultVO(401, "注册失败", null);
            } else {
                return new ResultVO(401, "此用户已注册", null);
            }
        }
    }


    @Override
    public ResultVO login(Users users) {
        String username = users.getUsername();
        String password = users.getPassword();
        //对密码进行MD5加密
        String passwordMD5 = SecureUtil.md5(password);
        //查询数据库 验证账号密码
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password",passwordMD5);
        List<Users> users2 = usersMapper.selectList(wrapper);
        if(users2==null||users2.isEmpty()){
            return new ResultVO(401,"账号或密码错误",null);
        }else {
            //获取用户
            Users user = users2.get(0);
            //通过JWt生成token
            String token = jwtToken.generateToken(user);
            //返回token及用户信息
            return new ResultVO(200,token,user);
        }
    }
}


